package com.yonyou.brigade.cron.order.ybz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.*;
import com.yonyou.brigade.order_center.service.IBriCarOrderService;
import com.yonyou.brigade.order_center.service.IBriFlightOrderService;
import com.yonyou.brigade.order_center.service.IBriHotelOrderService;
import com.yonyou.brigade.order_center.service.IBriTrainOrderService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.brigade.ybz.model.BriOrderNote;
import com.yonyou.brigade.ybz.service.IBriOrderNoteService;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.elasticjob.lite.annotation.ElasticJobConfig;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 将订单通过转换平台转为记事后推送友报账
 *
 * @Auther: kfw
 * @Date: 2018/8/27 11:18
 * @Description:
 */

@ElasticJobConfig(cron = "0 0 6 * * ? ", shardingTotalCount = 1)
@Component
@PropertySource("classpath:/config/bdsdk.properties")
public class PushOrderToYBZ implements SimpleJob {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("briFlightOrderServiceImpl")
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    @Qualifier("briHotelOrderServiceImpl")
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    @Qualifier("briTrainOrderServiceImpl")
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    @Qualifier("briCarOrderServiceImpl")
    private IBriCarOrderService briCarOrderService;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    private IBriOrderNoteService briOrderNoteService;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;
    @Value("${cnv.brigade.flight.tradetype}")
    private String flightTradetype;
    @Value("${cnv.brigade.hotel.tradetype}")
    private String hotelTradetype;
    @Value("${cnv.brigade.train.tradetype}")
    private String trainTradetype;
    @Value("${cnv.brigade.car.tradetype}")
    private String carTradetype;
    @Value("${brigade.cur}")
    private String curEnv;
    @Value("${ybz.getNodeState.url}")
    private String getNodeStateUrl;
    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    private static final String DATEFORMAT = "yyyy-MM-dd";

    @Override
    public void execute(ShardingContext shardingContext) {
        if (curEnv.equals("develop") || curEnv.equals("release")) {
            return;
        }
        List<BriChannel> briChannels = briChannelService.getDistinctEnableChannelGroupByTenant();
        if (briChannels != null && briChannels.size() > 0) {
            for (BriChannel briChannel : briChannels) {
                //判断是否需要生成记事
//                if (0 == briChannel.getNeedOrderToNote()) {
//                    continue;
//                }
                Map<String, String> flightParams = new HashMap<>();
                // 按租户以及国内、正常单查询并推送
                flightParams.put("tenant", briChannel.getTenant());
//                flightParams.put("is_domc", "D");
                // staus_type 和 order_type 均为正常单-退票单 但是 status_type 为空
                flightParams.put("order_type", "N");
                flightParams.put("order_status", "NP");
                flightParams.put("public_or_private", "1");
                SimpleDateFormat sf = new SimpleDateFormat(DATEFORMAT);
                Date yesterday = null;
                Date twoDaysBeforeYesterday = null;
                Date twoMonthsBeforeYesterday = null;
                try {
                    yesterday = sf.parse(DateUtils.getCurrentDateMinusOneDay(DATEFORMAT));
                    twoDaysBeforeYesterday = sf.parse((DateUtils.getCurrentDateMinusThreeDays(DATEFORMAT)));
                    twoMonthsBeforeYesterday = sf.parse(DateUtils.getCurrentDateMinusTwoMonths(DATEFORMAT));
                } catch (ParseException e) {
                    logger.error("日期转换错误！" + e.getMessage());
                }
                List<CnvFlightOrderDO> flightOrderDOs = briFlightOrderService.getCnvFlightOrderDos(flightParams, twoDaysBeforeYesterday, yesterday);
                for (CnvFlightOrderDO flightOrderDO : flightOrderDOs) {
                    if (!StringUtils.isEmpty(flightOrderDO.getUserId())) {
                        String relateYbzId = flightOrderDO.getRelateYbzId();
                        push(flightOrderDO.getUserId(), flightOrderDO.getTenant(), relateYbzId, flightTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(flightOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                    }
                }

                Map<String, String> hotelParams = new HashMap<>();
                hotelParams.put("tenant", briChannel.getTenant());
//                hotelParams.put("is_domc", "D");
                List<CnvHotelOrderDO> hotelOrderDOS = briHotelOrderService.getCnvHotelOrderDos(hotelParams, twoDaysBeforeYesterday, yesterday);
                for (CnvHotelOrderDO hotelOrderDO : hotelOrderDOS) {
                    if (!StringUtils.isEmpty(hotelOrderDO.getUserId())) {
                        String relateYBZID = hotelOrderDO.getRelateYBZID();
                        push(hotelOrderDO.getUserId(), hotelOrderDO.getTenant(), relateYBZID, hotelTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(hotelOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                    }
                }

                Map<String, String> trainParams = new HashMap<>();
                // 按租户以及正常单查询并推送
                trainParams.put("tenant", briChannel.getTenant());
                List<CnvTrainOrderDO> trainOrderDOs = briTrainOrderService.getCnvTrainOrderDos(trainParams, twoDaysBeforeYesterday, yesterday);
                for (CnvTrainOrderDO cnvTrainOrderDO : trainOrderDOs) {
                    if (!StringUtils.isEmpty(cnvTrainOrderDO.getUserId())) {
                        String relateYBZID = cnvTrainOrderDO.getRelateYBZID();
                        push(cnvTrainOrderDO.getUserId(), cnvTrainOrderDO.getTenant(), relateYBZID, trainTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvTrainOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                    }

                }

                Map<String, String> carParams = new HashMap<>();
                // 按租户以及正常单查询并推送
                carParams.put("tenant", briChannel.getTenant());
                List<CnvCarOrderDO> carOrderDOs = briCarOrderService.getCnvCarOrderDos(carParams, twoDaysBeforeYesterday, yesterday);
                for (CnvCarOrderDO cnvCarOrderDO : carOrderDOs) {
                    if (!StringUtils.isEmpty(cnvCarOrderDO.getUserId())) {
                        String relateYBZID = cnvCarOrderDO.getInApproveId();
                        push(cnvCarOrderDO.getUserId(), cnvCarOrderDO.getTenant(), relateYBZID, carTradetype, JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvCarOrderDO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat)));
                    }

                }
                //更新已生成记事的订单报销状态
                updateFlightBxStatus(briChannel.getTenant(), yesterday, twoMonthsBeforeYesterday);
                updateTrainBxStatus(briChannel.getTenant(), yesterday, twoMonthsBeforeYesterday);
                updateHotelBxStatus(briChannel.getTenant(), yesterday, twoMonthsBeforeYesterday);
                updateCarBxStatus(briChannel.getTenant(), yesterday, twoMonthsBeforeYesterday);
            }
        }
    }

    private void updateCarBxStatus(String tenant, Date yesterday, Date twoMonthsBeforeYesterday) {
        Wrapper<BriCarOrder> briCarOrderWrapper = new EntityWrapper<>();
        briCarOrderWrapper.where("tenant={0}", tenant);
        briCarOrderWrapper.and("is_note={0}", 1);
        briCarOrderWrapper.between("in_create_time", twoMonthsBeforeYesterday, yesterday);
        List<BriCarOrder> briCarOrders = briCarOrderService.selectList(briCarOrderWrapper);
        if (!CollectionUtils.isEmpty(briCarOrders)) {
            String notePks = "";
            for (BriCarOrder briCarOrder : briCarOrders) {
                Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                briOrderNoteWrapper.where("order_id={0}", briCarOrder.getId());
                briOrderNoteWrapper.and("order_type={0}", "car_order");
                List<BriOrderNote> briOrderNotes = briOrderNoteService.selectList(briOrderNoteWrapper);
                if (!CollectionUtils.isEmpty(briOrderNotes)) {
                    if (StringUtils.isEmpty(notePks)) {
                        notePks = briOrderNotes.get(0).getNotePk();
                    } else {
                        notePks = notePks + "," + briOrderNotes.get(0).getNotePk();
                    }
                }
            }
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            JSONObject paramJson = new JSONObject();
            paramJson.put("tenantid", tenant);
            paramJson.put("nodepks", notePks);
            logger.info("调用报账服务查询报销状态，参数为：" + paramJson.toJSONString());
            String res = HttpClientUtil.post(ybzBaseUrl + getNodeStateUrl, headers, null, paramJson.toJSONString());
            logger.info("调用报账服务查询报销状态，返回值为：" + res);
            if (!StringUtils.isEmpty(res)) {
                JSONObject resJson = JSONObject.parseObject(res);
                JSONArray datas = resJson.getJSONArray("data");
                if (datas != null && datas.size() > 0) {
                    for (Object o : datas) {
                        JSONObject dataJson = (JSONObject) o;
                        String nodeExpenseStatus = dataJson.getString("nodeExpenseStatus");
                        String nodePk = dataJson.getString("nodePk");
                        Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                        briOrderNoteWrapper.where("note_pk={0}", nodePk);
                        BriOrderNote briOrderNote = briOrderNoteService.selectOne(briOrderNoteWrapper);
                        if (!CollectionUtils.isEmpty(briCarOrders)) {
                            for (BriCarOrder briCarOrder : briCarOrders) {
                                if (briOrderNote.getOrderId().equals(String.valueOf(briCarOrder.getId()))) {
                                    briCarOrder.setBxState(StringUtils.isEmpty(nodeExpenseStatus) ? 101 : Integer.valueOf(nodeExpenseStatus));
                                    briCarOrderService.updateById(briCarOrder);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void updateHotelBxStatus(String tenant, Date yesterday, Date twoMonthsBeforeYesterday) {
        Wrapper<BriHotelOrder> briHotelOrderWrapper = new EntityWrapper<>();
        briHotelOrderWrapper.where("tenant={0}", tenant);
        briHotelOrderWrapper.and("is_note={0}", 1);
        briHotelOrderWrapper.between("order_time", twoMonthsBeforeYesterday, yesterday);
        List<BriHotelOrder> briHotelOrders = briHotelOrderService.selectList(briHotelOrderWrapper);
        if (!CollectionUtils.isEmpty(briHotelOrders)) {
            String notePks = "";
            for (BriHotelOrder briHotelOrder : briHotelOrders) {
                Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                briOrderNoteWrapper.where("order_id={0}", briHotelOrder.getId());
                briOrderNoteWrapper.and("order_type={0}", "hotel_order");
                List<BriOrderNote> briOrderNotes = briOrderNoteService.selectList(briOrderNoteWrapper);
                if (!CollectionUtils.isEmpty(briOrderNotes)) {
                    if (StringUtils.isEmpty(notePks)) {
                        notePks = briOrderNotes.get(0).getNotePk();
                    } else {
                        notePks = notePks + "," + briOrderNotes.get(0).getNotePk();
                    }
                }
            }
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            JSONObject paramJson = new JSONObject();
            paramJson.put("tenantid", tenant);
            paramJson.put("nodepks", notePks);
            logger.info("调用报账服务查询报销状态，参数为：" + paramJson.toJSONString());
            String res = HttpClientUtil.post(ybzBaseUrl + getNodeStateUrl, headers, null, paramJson.toJSONString());
            logger.info("调用报账服务查询报销状态，返回值为：" + res);
            if (!StringUtils.isEmpty(res)) {
                JSONObject resJson = JSONObject.parseObject(res);
                JSONArray datas = resJson.getJSONArray("data");
                if (datas != null && datas.size() > 0) {
                    for (Object o : datas) {
                        JSONObject dataJson = (JSONObject) o;
                        String nodeExpenseStatus = dataJson.getString("nodeExpenseStatus");
                        String nodePk = dataJson.getString("nodePk");
                        Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                        briOrderNoteWrapper.where("note_pk={0}", nodePk);
                        BriOrderNote briOrderNote = briOrderNoteService.selectOne(briOrderNoteWrapper);
                        if (!CollectionUtils.isEmpty(briHotelOrders)) {
                            for (BriHotelOrder briHotelOrder : briHotelOrders) {
                                if (briOrderNote.getOrderId().equals(String.valueOf(briHotelOrder.getId()))) {
                                    briHotelOrder.setBxStatus(StringUtils.isEmpty(nodeExpenseStatus) ? 101 : Integer.valueOf(nodeExpenseStatus));
                                    briHotelOrderService.updateById(briHotelOrder);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void updateTrainBxStatus(String tenant, Date yesterday, Date twoMonthsBeforeYesterday) {
        Wrapper<BriTrainOrder> briTrainOrderWrapper = new EntityWrapper<>();
        briTrainOrderWrapper.where("tenant={0}", tenant);
        briTrainOrderWrapper.and("is_note={0}", 1);
        briTrainOrderWrapper.between("order_time", twoMonthsBeforeYesterday, yesterday);
        List<BriTrainOrder> briTrainOrders = briTrainOrderService.selectList(briTrainOrderWrapper);
        if (!CollectionUtils.isEmpty(briTrainOrders)) {
            String notePks = "";
            for (BriTrainOrder briTrainOrder : briTrainOrders) {
                Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                briOrderNoteWrapper.where("order_id={0}", briTrainOrder.getId());
                briOrderNoteWrapper.and("order_type={0}", "brigade_trainDo_tradetype");
                List<BriOrderNote> briOrderNotes = briOrderNoteService.selectList(briOrderNoteWrapper);
                if (!CollectionUtils.isEmpty(briOrderNotes)) {
                    if (StringUtils.isEmpty(notePks)) {
                        notePks = briOrderNotes.get(0).getNotePk();
                    } else {
                        notePks = notePks + "," + briOrderNotes.get(0).getNotePk();
                    }
                }
            }
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            JSONObject paramJson = new JSONObject();
            paramJson.put("tenantid", tenant);
            paramJson.put("nodepks", notePks);
            logger.info("调用报账服务查询报销状态，参数为：" + paramJson.toJSONString());
            String res = HttpClientUtil.post(ybzBaseUrl + getNodeStateUrl, headers, null, paramJson.toJSONString());
            logger.info("调用报账服务查询报销状态，返回值为：" + res);
            if (!StringUtils.isEmpty(res)) {
                JSONObject resJson = JSONObject.parseObject(res);
                JSONArray datas = resJson.getJSONArray("data");
                if (datas != null && datas.size() > 0) {
                    for (Object o : datas) {
                        JSONObject dataJson = (JSONObject) o;
                        String nodeExpenseStatus = dataJson.getString("nodeExpenseStatus");
                        String nodePk = dataJson.getString("nodePk");
                        Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                        briOrderNoteWrapper.where("note_pk={0}", nodePk);
                        BriOrderNote briOrderNote = briOrderNoteService.selectOne(briOrderNoteWrapper);
                        if (!CollectionUtils.isEmpty(briTrainOrders)) {
                            for (BriTrainOrder briTrainOrder : briTrainOrders) {
                                if (briOrderNote.getOrderId().equals(String.valueOf(briTrainOrder.getId()))) {
                                    briTrainOrder.setBxStatus(StringUtils.isEmpty(nodeExpenseStatus) ? 101 : Integer.valueOf(nodeExpenseStatus));
                                    briTrainOrderService.updateById(briTrainOrder);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void updateFlightBxStatus(String tenant, Date yesterday, Date twoMonthsBeforeYesterday) {
        Wrapper<BriFlightOrder> briFlightOrderWrapper = new EntityWrapper<>();
        briFlightOrderWrapper.where("tenant={0}", tenant);
        briFlightOrderWrapper.and("is_note={0}", 1);
        briFlightOrderWrapper.between("order_time", twoMonthsBeforeYesterday, yesterday);
        List<BriFlightOrder> briFlightOrders = briFlightOrderService.selectList(briFlightOrderWrapper);
        if (!CollectionUtils.isEmpty(briFlightOrders)) {
            String notePks = "";
            for (BriFlightOrder briFlightOrder : briFlightOrders) {
                Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                briOrderNoteWrapper.where("order_id={0}", briFlightOrder.getId());
                briOrderNoteWrapper.and("order_type={0}", "flight_order");
                List<BriOrderNote> briOrderNotes = briOrderNoteService.selectList(briOrderNoteWrapper);
                if (!CollectionUtils.isEmpty(briOrderNotes)) {
                    if (StringUtils.isEmpty(notePks)) {
                        notePks = briOrderNotes.get(0).getNotePk();
                    } else {
                        notePks = notePks + "," + briOrderNotes.get(0).getNotePk();
                    }
                }
            }
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            JSONObject paramJson = new JSONObject();
            paramJson.put("tenantid", tenant);
            paramJson.put("nodepks", notePks);
            logger.info("调用报账服务查询报销状态，参数为：" + paramJson.toJSONString());
            String res = HttpClientUtil.post(ybzBaseUrl + getNodeStateUrl, headers, null, paramJson.toJSONString());
            logger.info("调用报账服务查询报销状态，返回值为：" + res);
            if (!StringUtils.isEmpty(res)) {
                JSONObject resJson = JSONObject.parseObject(res);
                JSONArray datas = resJson.getJSONArray("data");
                if (datas != null && datas.size() > 0) {
                    for (Object o : datas) {
                        JSONObject dataJson = (JSONObject) o;
                        String nodeExpenseStatus = dataJson.getString("nodeExpenseStatus");
                        String nodePk = dataJson.getString("nodePk");
                        Wrapper<BriOrderNote> briOrderNoteWrapper = new EntityWrapper<>();
                        briOrderNoteWrapper.where("note_pk={0}", nodePk);
                        BriOrderNote briOrderNote = briOrderNoteService.selectOne(briOrderNoteWrapper);
                        if (!CollectionUtils.isEmpty(briFlightOrders)) {
                            for (BriFlightOrder briFlightOrder : briFlightOrders) {
                                if (briOrderNote.getOrderId().equals(String.valueOf(briFlightOrder.getId()))) {
                                    briFlightOrder.setBxStatus(StringUtils.isEmpty(nodeExpenseStatus) ? 101 : Integer.valueOf(nodeExpenseStatus));
                                    briFlightOrderService.updateById(briFlightOrder);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void push(String userId, String tenant, String relateYBZID, String tradeType, JSONObject jsonObject) {
        /**
         * 1.HTTPCLIENT请求转换平台转换数据
         * 2.组装参数
         * 3.调用报账服务dubbo保存记事
         */
        //tenant = "zrez2bx9";
        JSONObject cnvFlightOrder = convertService.convert(tradeType, systemCode, userId, tenant, null, jsonObject);
        Map<String, List<Map<String, Object>>> noteMap = new HashMap<>();
        List<Map<String, Object>> noteList = new ArrayList<>();
        if (cnvFlightOrder.getBoolean("success")) {
            JSONArray noteJsonArray = cnvFlightOrder.getJSONArray("result");
            if (noteJsonArray != null && noteJsonArray.size() > 0) {
                for (int i = 0; i < noteJsonArray.size(); i++) {
                    JSONObject data = noteJsonArray.getJSONObject(i).getJSONObject("data");
                    if (CollectionUtils.isEmpty(data)) {
                        return;
                    }
                    data.put("orderId", jsonObject.getString("id"));
                    noteList.add(data);
                    noteMap.put(noteJsonArray.getJSONObject(i).getString("desbilltypecode"), noteList);
                    //绿城租户：若有申请单号，则该订单的记事生成到申请单的申请人账号下；若没有申请单，则依然生成记事到预订人账号下
                    if ("x0tc1f2v".equals(tenant) && !StringUtils.isEmpty(relateYBZID)) {
                        dealWithUserId(userId, relateYBZID, tenant);
                    }
                }
                convertService.pushToYBZ(noteMap, userId, tenant, tradeType, jsonObject.getString("id"));
            }
        } else {
            // 为了对在数据转换中出现错误的数据在推送服务中进行错误处理以及提醒
            convertService.pushToYBZ(noteMap, userId, tenant, tradeType, jsonObject.getString("id"));
        }
    }

    /**
     * 处理绿城租户的生成记事的逻辑，即有申请单的，记事生成给申请人
     * * @param userId
     *
     * @param relateYBZID
     * @param tenant
     */
    private void dealWithUserId(String userId, String relateYBZID, String tenant) {
        ArrayList<String> userIds = new ArrayList<>();
        userIds.add(userId);
        List<UcUserDto> completeUcUserDtoByUserid = iUserCenterService.getCompleteUcUserDtoByUserid(userIds, tenant);
        if (!completeUcUserDtoByUserid.isEmpty()) {
            UcUserDto ucUserDto = completeUcUserDtoByUserid.get(0);
            String phone = ucUserDto.getPhone();
            if (!StringUtils.isEmpty(phone)) {
                ArrayList<String> relateYBZIDs = new ArrayList<>();
                relateYBZIDs.add(relateYBZID);
                //拼请求参数
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("tenant", tenant);
                paramMap.put("pagenum", 10);
                paramMap.put("pks", relateYBZIDs);
                paramMap.put("page", 1);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                String res = HttpClientUtil.post("https://ybz.yonyoucloud.com/open/brigade/apply/findApplyByPks?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (!resObject.getJSONArray("data").isEmpty()) {
                        for (int j = 0; j < resObject.getJSONArray("data").size(); j++) {
                            JSONObject data1 = resObject.getJSONArray("data").getJSONObject(j);
                            if (data1.getBoolean("success")) {
                                JSONArray pk = data1.getJSONArray("pk");
                                if (pk != null && pk.size() > 0 && pk.contains(relateYBZID)) {
                                    JSONObject data = data1.getJSONObject("data");
                                    if (data != null && data.getBoolean("success")) {
                                        JSONArray datas = data.getJSONArray("data");
                                        if (datas != null && datas.size() > 0) {
                                            for (int k = 0; k < datas.size(); k++) {
                                                JSONObject dataObject = (JSONObject) datas.get(k);
                                                if (!dataObject.isEmpty() && "applyUser".equals(dataObject.getString("source_code"))) {
                                                    JSONObject default_value = dataObject.getJSONObject("default_value");
                                                    if (!default_value.isEmpty() && !StringUtils.isEmpty(default_value.get("id"))) {
                                                        userId = String.valueOf(default_value.get("id"));
                                                    } else {
                                                        logger.info("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单申请人的id为空,故此订单不生成记事");
                                                        return;
                                                    }
                                                }
                                            }
                                        } else {
                                            logger.info("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单结果为空,故此订单不生成记事");
                                            return;
                                        }
                                    } else {
                                        logger.error("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单内容出现异常");
                                        throw new BusinessException("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单内容出现异常");
                                    }
                                }
                            } else {
                                logger.error("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单出现异常");
                                throw new BusinessException("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单出现异常");
                            }
                        }
                    } else {
                        logger.info("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单结果为空,故此订单不生成记事");
                        return;
                    }
                } else {
                    logger.error("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单出现异常");
                    throw new BusinessException("绿城租户phone为" + phone + "，relateYBZID为" + relateYBZID + "向友报账请求查询相关申请单出现异常");
                }
            } else {
                logger.info("userId为" + userId + "的绿城用户到用户中心查得手机号为空");
            }
        } else {
            logger.info("通过绿城用户userId" + userId + "到用户中心查不到相关用户信息");
        }
    }
}
